/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eulerframework;

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.UIManager;

/**
 *
 * @author Thor
 */
public class Framework {

    private static List<Problem> problems = new LinkedList<Problem>();
    private static int current;
    private static MainFrame currentFrame;

    public static void start() {
        //add all the problems we find
        ClassFinder cf = new ClassFinder();
        List<Class<?>> classes = cf.findSubclasses("eulerframework.Problem");
        for(Class c : classes){
            try {
                if(c == DummyProblem.class)
                    continue;
                Problem p = (Problem) c.newInstance();
                addProblem(p);
            } catch (InstantiationException ex) {
                ex.printStackTrace();
            } catch (IllegalAccessException ex) {
                ex.printStackTrace();
            }
        }
        //start the framework
        sortProblems();
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        current = problems.size() - 1;
        currentFrame = problems.get(current).getFrame();
        currentFrame.setVisible(true);
    }

    public static void sortProblems(){
        Collections.sort(problems, new Comparator<Problem>() {

            public int compare(Problem o1, Problem o2) {
                return o1.getProblemNumber() - o2.getProblemNumber();
            }
        });
    }

    public static void gotoProblem(int n) throws ProblemNotFoundException {
        for (int i = 0; i < problems.size(); i++) {
            if (problems.get(i).getProblemNumber() == n) {
                //we found a matching problem!
                current = i;
                swapFrames(current);
                return;
            }
        }
        problems.add(new DummyProblem(n));
        sortProblems();
        gotoProblem(n);
    }

    private static void swapFrames(int next) {
        MainFrame newFrame = problems.get(next).getFrame();
        currentFrame.setVisible(false);
        newFrame.setLocation(currentFrame.getX(), currentFrame.getY());
        newFrame.setSize(currentFrame.getSize());
        newFrame.setVisible(true);
        currentFrame = newFrame;
    }

    public static void addProblem(Problem p) {
        problems.add(p);
    }

    public static void nextProblem() {
        if (current + 1 == problems.size()) {
            return;
        }
        current++;
        swapFrames(current);
    }

    public static void previousProblem() {
        if (current - 1 < 0) {
            return;
        }
        current--;
        swapFrames(current);
    }
}
